import Error from 'next/error'
import fetch from 'isomorphic-unfetch'

const Page = ({hasError, stars}) => {
  if (hasError) {
    return <Error statusCode={501}/>
    /*
    The Error component also takes title as a property
    if you want to pass in a text message along with a statusCode.
    */
  }

  return <div>Next stars: {stars}</div>
};

Page.getInitialProps = async () => {
  let hasError
    ,json;
  console.log('Page.getInitialProps');
  // const res = await fetch('https://api.github.com/repos/zeit/next.js');
  try {
    const res = await fetch('https://api.github.com/repos/zeit/next1.js');
    json = await res.json();
  }catch (e) {
    hasError = true;
  }

  return {hasError, stars: json && json.stargazers_count}
};

export default Page
